import { showMyMessageBox } from "@/components/MyMessageBox";

import { defineStore } from 'pinia';

import { loginApi, logoutApi, getReturncode, loginCoceApi} from '@/api/auth';
import { getUserInfo } from '@/api/user';
import { resetRouter } from '@/router';
import { store } from '@/store';

import { LoginData } from '@/api/auth/types';
import { MenuTree, UserInfo, MenuTreeVue } from '@/api/user/types';
import { TenantRelaOV } from '@/api/tenant/types'

import { useStorage } from '@vueuse/core';
import { el } from 'element-plus/es/locale';
import { Callback } from "element-plus";

export const useUserStore = defineStore('user', () => {
  // state
  const token = useStorage('accessToken', '');
  const nickname = ref('');
  const avatar = ref('');
  const menuTree = ref<Array<MenuTree>>([]);
  const menuTreeVue = ref<Array<MenuTreeVue>>([]);
  const userInfo = ref<UserInfo>({
  });
  /**
   * 登录调用
   *
   * @param {LoginData}
   * @returns
   */
  function loginA(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((res: any) => {
          const atoken = res.data.token;
          token.value = 'Bearer' + ' ' + atoken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  }

   /**
     * 登录
     */
   function login(data: any) {
    const { phone, password, code, tabIndex, userName } = data;
    if (tabIndex == 0) {
      return new Promise((resolve, reject) => {
        loginApi({
          userName: userName,
          password: password
        })
          .then((res: any) => {
            const atoken = res.data.token;
            token.value = 'Bearer' + ' ' + atoken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
            resolve(res.data);
          })
          .catch(error => {
            console.log(error)
            reject(error);
          });
      });
    } else {
      return new Promise((resolve, reject) => {
        loginCoceApi({
          phone: phone.trim(),
          code
        })
          .then((res: any) => {
            const atoken = res.data.token;
            token.value = 'Bearer' + ' ' + atoken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
            resolve(res.data);
          })
          .catch(error => {
            console.log(error)
            reject(error);
          });
      });
    }
  }

  function getCode(data: any) {
    return  getReturncode(data).then((res: any) => {
      // ElMessage.success(res.data.code);
      return res.data
    })
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo() {
    return getUserInfo()
      .then((res) => {
        nickname.value = res.data.userInfo.nickName || '';
        avatar.value = res.data.avatar;
        menuTree.value = res.data.menuTree
        menuTreeVue.value = res.data.menuTreeVue;
        userInfo.value = res.data.userInfo;
        useStorage('userInfo', res.data.userInfo)

        return res.data
      }).catch((err) => {
        new Error(err)
      })

  }

  // 注销
  function logout() {
    return logoutApi({
      id: userInfo.value.id
    })
      .then(() => {
        resetToken();
      })
      .catch(error => {
        new Error(error);
      });

  }

  // 重置
  function resetToken() {
    token.value = '';
    nickname.value = '';
    avatar.value = '';
    menuTree.value = [];
    userInfo.value = {};
    menuTreeVue.value = [];
    useStorage('userInfo', {});
    // resetRouter();
  }
  return {
    token,
    nickname,
    avatar,
    menuTree,
    menuTreeVue,
    userInfo,
    login,
    getInfo,
    logout,
    resetToken,
    getCode
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
